from threading import Thread

from flask import Flask, render_template, request, redirect, url_for, flash
from flask_mail import Mail, Message

app = Flask(__name__)

# 配置邮件参数
app.config['MAIL_SERVER'] = 'smtp.qq.com'  # QQ邮箱的SMTP服务器地址
app.config['MAIL_PORT'] = 587  # QQ邮箱的SMTP服务器端口，通常为587
app.config['MAIL_USE_TLS'] = True  # 启用TLS加密
app.config['MAIL_USERNAME'] = '2362262019@qq.com'  # 使用你的QQ邮箱账号
app.config['MAIL_PASSWORD'] = 'xcelzwteqccweahc'  # 使用你的QQ邮箱的授权码
app.config['MAIL_DEFAULT_SENDER'] = '2362262019@qq.com'  # 默认发件人地址，使用你的QQ邮箱账号

app.secret_key = 'qweasdzxc'
# 初始化邮件扩展
mail = Mail(app)


def send_async_email(app, msg):
    with app.app_context():
        mail.send(msg)


@app.route('/', methods=['GET', 'POST'])
def send_email():
    if request.method == 'POST':
        recipient = request.form['recipient']
        print(recipient)
        subject = request.form['subject']
        body = request.form['body']

        try:
            # 创建邮件消息
            message = Message(subject=subject, recipients=[recipient], body=body)

            # 发送邮件
            # mail.send(message)
            # 异步发送
            thr = Thread(target=send_async_email, args=[app, message])
            thr.start()

            flash('邮件发送成功！', 'success')
            return redirect(url_for('send_email'))

        except Exception as e:
            flash(f'邮件发送失败：{e}', 'error')

    return render_template('send_email.html')


if __name__ == '__main__':
    app.run(debug=True)
